package com.socket.netty;

import com.socket.batch.collector.DataAnalysis;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;

import java.util.Date;

/**
 * Created by kaddddd on 2017/7/4 0004.
 */
public class LoginClientHandler extends ChannelInboundHandlerAdapter {
    private static final transient Logger log = Logger.getLogger(LoginClientHandler.class);

    private int counter;

    public final ByteBuf firstMessage;

    public LoginClientHandler(){
        //String s = "5B000000480000000010010007C93201000000000000000007C93238363132383733313232312E31302E32322E313730000000000000000000000000000000000000001F99E7C55D";
        //String s = "5B0000005A020000000F120000BC614E0100010000000000C3F6423030303030000000000000000000000000000112020000002400130607E10F0A220686805F023B4585003E0046000016C600530033000000130000000066305D";
        String s = "5B0000004800000D46100100BC614E010001000000000000BC614E31323334353637383132372E302E302E310000000000000000000000000000000000000000000000270882A65D";
        byte[] req = DataAnalysis.hex2Bytes(s);
        firstMessage = Unpooled.copiedBuffer(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("LoginClientHandler.channelActive");
//        System.out.println("----------------handler channelActive-----准备发送一个数据-------");
//        //String s = "5B0000005A020000000F120000BC614E0100010000000000C3F6423030303030000000000000000000000000000112020000002400130607E10F0A220686805F023B4585003E0046000016C600530033000000130000000066305D";
//        String s = "5B000000480000000010010007C93201000000000000000007C93238363132383733313232312E31302E32322E313730000000000000000000000000000000000000001F99E7C55D";
//        byte[] req = DataAnalysis.hex2Bytes(s);
        ctx.writeAndFlush(firstMessage);
        System.out.println("发送消息完毕");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("LoginClientHandler.channelRead");
        try {
            System.out.println("this is"+ ++counter +"--------channelRead---服务器发来的数据为：[" + msg + "]");
            //ctx.close();
        } finally {
            //ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("----------------handler channelReadComplete");
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("---------------exceptionCaught 网络异常，关闭网络");
        cause.printStackTrace();
        ctx.close();
    }
}